package com.example.myone.Mapper;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myone.Entity.User;
import com.example.myone.R;
import com.example.myone.Util.ImageUtils;
import com.example.myone.Util.PasswordEncryptor;
import com.example.myone.sql.MySQLiteHelper;

import java.util.ArrayList;
import java.util.List;

public class UserMapper {
    private static final String TABLE_NAME = "user";

    // 插入一个用户
    public static User insertUser(Context context, User user) {
        SQLiteDatabase db = MySQLiteHelper.getWritableDatabase(context);
        ContentValues values = new ContentValues();
        values.put("account", user.account);
        values.put("password", user.password);
        values.put("username", user.username);
        values.put("avatar", user.avatar);
        values.put("background", user.background);
        long insert = db.insert(TABLE_NAME, null, values);
        user.id = (int) insert;
        return user;
    }

    // 根据 ID 获取用户
    public static User getUserById(Context context, Integer id) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where id = ?",
                new String[]{id.toString()});
        List<User> users = getUsers(cursor);
        return users.isEmpty() ? null : users.get(0);
    }

    // 根据账号获取用户
    public static User getUserByAccount(Context context, String account) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        Cursor cursor = database.rawQuery(
                "select * from " + TABLE_NAME + " where account = ?",
                new String[]{account});
        List<User> users = getUsers(cursor);
        return users.isEmpty() ? null : users.get(0);
    }

    // 检查 user 表是否有数据
    private static boolean isTableEmpty(Context context) {
        SQLiteDatabase database = MySQLiteHelper.getReadableSQLiteDatabase(context);
        try (Cursor cursor = database.rawQuery("select count(*) from " + TABLE_NAME, null)) {
            cursor.moveToFirst();
            return cursor.getInt(0) == 0;
        }
    }

    // 初始化方法
    @SuppressLint("NewApi")
    public static void init(Context context) {
        if (!isTableEmpty(context)) return;
        System.out.printf("==> 初始化 %s 数据库数据", TABLE_NAME);
        User user = new User();
        user.account = "user";
        user.password = PasswordEncryptor.encryptPassword("123456");
        user.username = "西小麦";
        user.avatar = ImageUtils.convertImageToBase64(context, R.drawable.article_image4);
        user.background = ImageUtils.convertImageToBase64(context, R.drawable.article_image3);
        insertUser(context, user);
        user.account = "baozi";
        user.password = PasswordEncryptor.encryptPassword("123456");
        user.username = "马晓晨";
        user.avatar = ImageUtils.convertImageToBase64(context, R.drawable.article_image5);
        user.background = ImageUtils.convertImageToBase64(context, R.drawable.article_image6);
        insertUser(context, user);

    }

    @SuppressLint("Range")
    public static ArrayList<User> getUsers(Cursor cursor) {
        ArrayList<User> users = new ArrayList<>();
        if (cursor != null && cursor.moveToFirst()) {
            do {
                User user = new User();
                user.id = cursor.getInt(cursor.getColumnIndex("id"));
                user.account = cursor.getString(cursor.getColumnIndex("account"));
                user.password = cursor.getString(cursor.getColumnIndex("password"));
                user.username = cursor.getString(cursor.getColumnIndex("username"));
                user.avatar = cursor.getString(cursor.getColumnIndex("avatar"));
                user.background = cursor.getString(cursor.getColumnIndex("background"));
                users.add(user);
            } while (cursor.moveToNext());
            cursor.close();
        }
        return users;
    }

    // 更新用户
    public static void updateUser(Context context, User user) {
        SQLiteDatabase db = MySQLiteHelper.getWritableDatabase(context);
        ContentValues values = new ContentValues();
        putIfNotNull(values, "account", user.account);
        putIfNotNull(values, "password", user.password);
        putIfNotNull(values, "username", user.username);
        putIfNotNull(values, "avatar", user.avatar);
        putIfNotNull(values, "background", user.background);
        db.update(TABLE_NAME, values, "id=?", new String[]{String.valueOf(user.id)});
    }

    private static <T> void putIfNotNull(ContentValues values, String key, T value) {
        if (value != null) {
            values.put(key, String.valueOf(value));
        }
    }

}
